#include "version_blck.h"
#include "ui_version_blck.h"
#include <QDir>
#include <QFileInfoList>
#include <QApplication>
#include <QDebug>
#include <QFileDialog>
#include <QDesktopServices>
#include <QUrl>
#include <QFileInfo>
#include <QMessageBox>
version_blck::version_blck(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::version_blck)
{
    ui->setupUi(this);
    ui->ui_prc_copy->setValue(0);
    time_lst = QDateTime::currentDateTime(); //初始化时间
    // --------------------------------------------
    // 加载默认的路径
    QString setting_ini = QApplication::applicationDirPath() + "/user_data/setting.ini";
    settings = new QSettings(setting_ini,QSettings::IniFormat);
    QString version_sync_dst = settings->value("version_sync_dst","").toString();
    ui->ui_lin_dir->setText(version_sync_dst); //加载同步目录
}

version_blck::~version_blck()
{
    delete ui;
}
//void version_blck::update_file_path(QList<QString> l_file)
//{
//    // read path from file_mdle
//    QString p_ver_release = l_file[P_VERSION_SYNC];
//    ui->ui_lin_dir->setText(p_ver_release);
//}

void version_blck::get_bug_file()
{
    QString startDirectoryVersion = QApplication::applicationDirPath() + "/version.md"; // 起始目录，这里以当前目录为例
    QString targetDirectoryVersion = ui->ui_lin_dir->text() +  "/version.md";
    forceCopyFile(targetDirectoryVersion,startDirectoryVersion); //提取发布程序的readme

    // 将文件路径转换为QUrl对象
    QUrl fileUrl = QUrl::fromLocalFile(targetDirectoryVersion);
    // 尝试打开文件
    if (QDesktopServices::openUrl(fileUrl)) {
        qDebug() << "文件已成功打开。";
        return;
    } else {
        qDebug() << "无法打开文件。" << targetDirectoryVersion;
        //如果打不开目标日志文件
    }
    // 将文件路径转换为QUrl对象
    QUrl fileUrl2 = QUrl::fromLocalFile(startDirectoryVersion); //如果发布文件不存在，则打开本地文件
    // 尝试打开文件
    if (QDesktopServices::openUrl(fileUrl2)) {
        qDebug() << "文件已成功打开。";
        return;
    } else {
        qDebug() << "无法打开文件。" << startDirectoryVersion;
        QFile file(startDirectoryVersion); //创建版本记录文件
        if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                qDebug() << "无法打开文件:";
        }
        file.close();
        QDesktopServices::openUrl(fileUrl2); //重新打开
        //如果打不开目标日志文件
    }
}
void version_blck::recursiveFileSearch(const QString& directory, const QStringList& suffixes, QStringList& result)
{
    QDir dir(directory);
    if (!dir.exists()) {
        return;
    }

    // 设置文件过滤器
    QStringList filters;
    for (const QString& suffix : suffixes) {
        filters.append("*." + suffix);
    }
    dir.setNameFilters(filters);

    // 只获取文件，忽略.和..
    dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
    QFileInfoList fileInfoList = dir.entryInfoList();
    for (const QFileInfo& fileInfo : fileInfoList) {
        result.append(fileInfo.absoluteFilePath());
    }

    // 递归处理子目录
    QDir dir2(directory);
    dir2.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
    QFileInfoList subDirInfoList = dir2.entryInfoList();
    for (const QFileInfo& subDirInfo : subDirInfoList) {
        //qDebug() << "子目录路径:" << subDirInfo.absoluteFilePath();
        recursiveFileSearch(subDirInfo.absoluteFilePath(), suffixes, result);
    }
}
bool version_blck::forceCopyFile(const QString& sourceFilePath, const QString& targetFilePath) {
    // 检查源文件是否存在
    if (!QFile::exists(sourceFilePath))
    {
        qDebug() << "error src" << sourceFilePath;
        return false;
    }
    if(sourceFilePath.contains(QApplication::applicationDirPath()+"/user_data/"))
    {
        //滤除特定目录的拷贝，防止测试的文件导入到正式版本的程序
        QDEBUG << "not copy user_data" << sourceFilePath;
        return true;
    }
    // 若目标文件已存在，先将其删除
    if (QFile::exists(targetFilePath))
    {
        //判断文件信息
        QFileInfo srcInfo(sourceFilePath);
        QFileInfo dstInfo(targetFilePath);
        QDateTime src_time_modified = srcInfo.lastModified();
        QDateTime dst_time_modified = dstInfo.lastModified();
        if(dst_time_modified != src_time_modified) //文件修改时间不一致
        {
            qDebug() << __FILE__ << __LINE__ << src_time_modified << dst_time_modified;
            //删除原有的文件
            if (!QFile::remove(targetFilePath)) {
                qDebug() << "error delete" << targetFilePath;
                return false;
            }
        }
        else
        {
            //文件一致不更新
            return true;
        }
    }

    // 复制文件
    if (!QFile::copy(sourceFilePath, targetFilePath))
    {
        qDebug() << sourceFilePath << "copy error" << targetFilePath;
        return false;
    }

    return true;
}
void version_blck::on_ui_btm_vsyn_clicked()
{
    QDateTime now = QDateTime::currentDateTime();
    if(time_lst.msecsTo(now) < 1000) //每次更新的间隔最少1s
    {
        return;
    }
    QDir dst_dir(ui->ui_lin_dir->text());
    if(!dst_dir.exists()) //目标目录不存在
    {
        QDEBUG << dst_dir << " not exist";
        return;
    }
    QString appFileName = QFileInfo(QCoreApplication::applicationFilePath()).fileName();
    if(! QFile::exists(dst_dir.filePath(appFileName)))
    {
        QDEBUG << appFileName << "not exist";
        QMessageBox::warning(this,"dir_check",
                             appFileName+" not found in " + ui->ui_lin_dir->text()
                             );
        return;
    }

    ui->ui_txt_result->clear();
    ui->ui_txt_result->append("===========================");
    ui->ui_txt_result->append("start update");
    QString startDirectory = QApplication::applicationDirPath(); // 起始目录，这里以当前目录为例
    QStringList suffixes = {"exe", "o","cpp","dll","qm","bat","png","ico"}; // 要获取的文件后缀
    QStringList foundFiles;

    recursiveFileSearch(startDirectory, suffixes, foundFiles);
    int i = 0;
    for (const QString& str : foundFiles)
    {
        QString src_file = str;
        ui->ui_txt_result->append(src_file);
        QString dst_file = src_file.replace(startDirectory,ui->ui_lin_dir->text());
        ui->ui_txt_result->append(dst_file);
        forceCopyFile(str,dst_file);
        ui->ui_txt_result->append("--------------------");
        ui->ui_prc_copy->setValue(i * 100 / foundFiles.length() );
        i = i + 1;
    }
    ui->ui_prc_copy->setValue(100);
    ui->ui_txt_result->append("finish update");
    time_lst = QDateTime::currentDateTime(); //记录下上次按钮结束的时间
}


void version_blck::on_ui_btm_dir_clicked()
{
    QString p_dir  = QFileDialog::getExistingDirectory
                            (this,
                             "Please choose an work dir",
                             "");
    if (p_dir.isEmpty())
    {
        qDebug() << "你取消了选择。";
        return;
    }
    ui->ui_lin_dir->setText(p_dir);
    settings->setValue("version_sync_dst",p_dir);

}

